"""
商品详情页面
显示商品的详细信息、厂商信息、用户评价等
"""

import tkinter as tk
from tkinter import ttk, messagebox
import customtkinter
from ui.pages.scrollable_page import ScrollablePage
from core.models.product import Product
from core.utils.logger import debug, info, warning, error
from core.utils.i18n import t
from core.utils.image_utils import load_thumbnail
from ui.components.star_rating import StarRating
from ui.components.review_card import ReviewCard
from ui.styles.theme import Theme
from datetime import datetime


class ProductDetailPage(ScrollablePage):
    """商品详情页面"""
    
    def __init__(self, parent, controller, product_id=None):
        """
        初始化商品详情页面
        
        Args:
            parent: 父窗口
            controller: 主控制器
            product_id: 商品ID
        """
        self.product_id = product_id
        self.product = None
        self.reviews = []
        self.quantity = 1  # 购买数量
        
        super().__init__(parent, controller)
    
    def create_widgets(self):
        """创建页面组件"""
        content = self.scrollable_frame
        
        # 创建顶部导航栏
        self.create_header(content)
        
        # 创建商品信息区域
        self.create_product_info_area(content)
        
        # 创建厂商信息区域
        self.create_manufacturer_area(content)
        
        # 创建用户评价区域
        self.create_reviews_area(content)
        
        # 创建底部操作栏
        self.create_action_bar(content)
        
        # 加载商品数据
        self.load_product_data()
    
    def create_header(self, parent):
        """创建顶部导航栏"""
        header_frame = customtkinter.CTkFrame(parent, fg_color="transparent")
        header_frame.pack(fill='x', padx=20, pady=(10, 20))
        
        # 返回按钮
        back_btn = customtkinter.CTkButton(
            header_frame, 
            text=t('product_detail.back_to_list'), 
            command=self.go_back,
            width=100
        )
        back_btn.pack(side='left')
        
        # 页面标题
        title_label = customtkinter.CTkLabel(
            header_frame, 
            text=t('product_detail.title'), 
            font=('Arial', 20, 'bold'),
            text_color=Theme.get_color('fg_primary')
        )
        title_label.pack(side='left', padx=(20, 0))
    
    def create_product_info_area(self, parent):
        """创建商品信息区域"""
        # 商品信息主容器
        self.product_info_frame = customtkinter.CTkFrame(parent, fg_color="transparent")
        self.product_info_frame.pack(fill='x', padx=20, pady=(0, 20))
        
        # 商品图片区域
        self.create_image_section()
        
        # 商品基本信息区域
        self.create_basic_info_section()
        
        # 商品描述区域
        self.create_description_section()
    
    def create_image_section(self):
        """创建商品图片区域"""
        image_frame = customtkinter.CTkFrame(self.product_info_frame, fg_color=("gray95", "gray20"))
        image_frame.pack(fill='x', pady=(0, 15), ipadx=15, ipady=15)
        
        # 区域标题
        customtkinter.CTkLabel(
            image_frame,
            text=f'🖼️ {t("product_detail.image_title")}',
            font=('Arial', 14, 'bold'),
            text_color=Theme.get_color('fg_primary')
        ).pack(anchor='w', pady=(0, 10))
        
        # 主图显示区域
        self.main_image_frame = ttk.Frame(image_frame, width=300, height=200)
        self.main_image_frame.pack(anchor='w')
        self.main_image_frame.pack_propagate(False)
        
        # 图片占位符
        self.image_placeholder = tk.Label(
            self.main_image_frame,
            text="🖼️\n" + t('product_detail.image_title'),
            font=("Arial", 16),
            fg="#999999",
            bg="#F8F9FA",
            justify="center",
            relief="solid",
            bd=1
        )
        self.image_placeholder.pack(fill="both", expand=True)
    
    def create_basic_info_section(self):
        """创建商品基本信息区域"""
        info_frame = customtkinter.CTkFrame(self.product_info_frame, fg_color=("gray95", "gray20"))
        info_frame.pack(fill='x', pady=(0, 15), ipadx=15, ipady=15)
        
        # 区域标题
        customtkinter.CTkLabel(
            info_frame,
            text=f'📋 {t("product_detail.basic_info_title")}',
            font=('Arial', 14, 'bold'),
            text_color=Theme.get_color('fg_primary')
        ).pack(anchor='w', pady=(0, 15))
        
        # 商品名称
        self.name_label = customtkinter.CTkLabel(
            info_frame,
            text="加载中...",
            font=('Arial', 18, 'bold'),
            text_color=Theme.get_color('fg_primary'),
            anchor='w'
        )
        self.name_label.pack(anchor='w', pady=(0, 15))
        
        # 价格和评分行
        price_rating_frame = customtkinter.CTkFrame(info_frame, fg_color="transparent")
        price_rating_frame.pack(fill='x', pady=(0, 15))
        
        # 价格
        self.price_label = customtkinter.CTkLabel(
            price_rating_frame,
            text="¥0.00",
            font=('Arial', 24, 'bold'),
            text_color='#E74C3C'
        )
        self.price_label.pack(side='left')
        
        # 评分区域
        rating_frame = customtkinter.CTkFrame(price_rating_frame, fg_color="transparent")
        rating_frame.pack(side='right')
        
        # 星级评分
        self.star_rating = StarRating(
            rating_frame,
            rating=0,
            editable=False,
            size=18
        )
        self.star_rating.pack(side='left', padx=(20, 5))
        
        # 评分文字
        self.rating_text_label = customtkinter.CTkLabel(
            rating_frame,
            text="(0 评价)",
            font=('Arial', 12),
            text_color=Theme.get_color('fg_secondary')
        )
        self.rating_text_label.pack(side='left')
        
        # 库存和类别信息
        info_bottom_frame = customtkinter.CTkFrame(info_frame, fg_color="transparent")
        info_bottom_frame.pack(fill='x')
        
        # 库存信息
        self.stock_label = customtkinter.CTkLabel(
            info_bottom_frame,
            text="库存: 加载中...",
            font=('Arial', 12, 'bold'),
            text_color='#27AE60'
        )
        self.stock_label.pack(side='left')
        
        # 商品类别
        self.category_label = customtkinter.CTkLabel(
            info_bottom_frame,
            text="",
            font=('Arial', 10),
            text_color=Theme.get_color('fg_secondary')
        )
        self.category_label.pack(side='right')
    
    def create_description_section(self):
        """创建商品描述区域"""
        desc_frame = customtkinter.CTkFrame(self.product_info_frame, fg_color=("gray95", "gray20"))
        desc_frame.pack(fill='x', pady=(0, 15), ipadx=15, ipady=15)
        
        # 区域标题
        customtkinter.CTkLabel(
            desc_frame,
            text=f'📝 {t("product_detail.description_title")}',
            font=('Arial', 14, 'bold'),
            text_color=Theme.get_color('fg_primary')
        ).pack(anchor='w', pady=(0, 10))
        
        # 描述文本
        self.description_text = tk.Text(
            desc_frame,
            height=6,
            wrap='word',
            font=('Arial', 10),
            state='disabled'
        )
        self.description_text.pack(fill='x')
        
        # 规格信息
        self.specs_frame = customtkinter.CTkFrame(desc_frame, fg_color="transparent")
        self.specs_frame.pack(fill='x', pady=(10, 0))
    
    def create_manufacturer_area(self, parent):
        """创建厂商信息区域"""
        self.manufacturer_frame = customtkinter.CTkFrame(parent, fg_color=("gray95", "gray20"))
        self.manufacturer_frame.pack(fill='x', padx=20, pady=(0, 20), ipadx=15, ipady=15)
        
        # 区域标题
        customtkinter.CTkLabel(
            self.manufacturer_frame,
            text=f'🏭 {t("product_detail.manufacturer_title")}',
            font=('Arial', 14, 'bold'),
            text_color=Theme.get_color('fg_primary')
        ).pack(anchor='w', pady=(0, 10))
        
        # 厂商名称
        self.manufacturer_name_label = customtkinter.CTkLabel(
            self.manufacturer_frame,
            text="厂商: 加载中...",
            font=('Arial', 12, 'bold'),
            text_color=Theme.get_color('fg_primary')
        )
        self.manufacturer_name_label.pack(anchor='w', pady=(0, 5))
        
        # 厂商详细信息
        self.manufacturer_info_label = customtkinter.CTkLabel(
            self.manufacturer_frame,
            text="详细信息加载中...",
            font=('Arial', 10),
            text_color=Theme.get_color('fg_secondary')
        )
        self.manufacturer_info_label.pack(anchor='w')
    
    def create_reviews_area(self, parent):
        """创建用户评价区域"""
        self.reviews_frame = customtkinter.CTkFrame(parent, fg_color=("gray95", "gray20"))
        self.reviews_frame.pack(fill='x', padx=20, pady=(0, 20), ipadx=15, ipady=15)
        
        # 区域标题 + 查看全部按钮
        header_row = customtkinter.CTkFrame(self.reviews_frame, fg_color="transparent")
        header_row.pack(fill='x', pady=(0, 15))
        customtkinter.CTkLabel(
            header_row,
            text=f'⭐ {t("product_detail.reviews_title")}',
            font=('Arial', 14, 'bold'),
            text_color=Theme.get_color('fg_primary')
        ).pack(side='left')
        view_all_btn = customtkinter.CTkButton(
            header_row,
            text='View All Reviews',
            width=120,
            command=self._open_all_reviews
        )
        view_all_btn.pack(side='right')
        
        # 评价统计
        self.reviews_stats_frame = customtkinter.CTkFrame(self.reviews_frame, fg_color="transparent")
        self.reviews_stats_frame.pack(fill='x', pady=(0, 15))
        
        # 评价列表容器
        self.reviews_list_frame = customtkinter.CTkFrame(self.reviews_frame, fg_color="transparent")
        self.reviews_list_frame.pack(fill='x')

    def _open_all_reviews(self):
        """打开全部评价页面"""
        try:
            if not self.product_id:
                messagebox.showwarning("警告", "商品ID无效，无法查看评价")
                error("Cannot open reviews page: product_id is None")
                return
            
            page = self.controller.pages.get('ProductReviewsPage')
            if not page:
                messagebox.showerror("错误", "评价页面未找到")
                error("ProductReviewsPage not found in controller pages")
                return
            
            # 安全获取商品名称
            product_name = ""
            if self.product:
                if hasattr(self.product, 'get_display_name'):
                    product_name = self.product.get_display_name()
                else:
                    product_name = getattr(self.product, 'name_en', None) or getattr(self.product, 'name', 'Unknown Product')
            else:
                # 如果没有商品对象，尝试从product_service获取
                try:
                    product = self.controller.product_service.get_product_by_id(self.product_id)
                    if product:
                        if hasattr(product, 'get_display_name'):
                            product_name = product.get_display_name()
                        else:
                            product_name = getattr(product, 'name_en', None) or getattr(product, 'name', 'Unknown Product')
                    else:
                        product_name = self.product_id
                except Exception as e:
                    error(f"Failed to get product name: {e}")
                    product_name = self.product_id
            
            info(f"Opening reviews page for product: {self.product_id}, name: {product_name}")
            page.set_product(self.product_id, product_name)
            self.controller.show_page('ProductReviewsPage')
            
        except Exception as e:
            error(f"Failed to open reviews page: {e}")
            import traceback
            error(f"Exception stack: {traceback.format_exc()}")
            messagebox.showerror("错误", f"无法打开评价页面: {e}")
    
    def create_action_bar(self, parent):
        """创建底部操作栏"""
        # 固定底部操作栏
        action_frame = customtkinter.CTkFrame(parent, fg_color="transparent")
        action_frame.pack(fill='x', padx=20, pady=(20, 0), side='bottom')
        
        # 添加分隔线
        customtkinter.CTkFrame(action_frame, height=2, fg_color=Theme.get_color('border_color')).pack(fill='x', pady=(0, 20))
        
        # 操作区域
        operation_frame = customtkinter.CTkFrame(action_frame, fg_color=("gray95", "gray20"))
        operation_frame.pack(fill='x', ipadx=20, ipady=15)
        
        # 数量选择
        quantity_frame = customtkinter.CTkFrame(operation_frame, fg_color="transparent")
        quantity_frame.pack(side='left', padx=(0, 30))
        
        customtkinter.CTkLabel(
            quantity_frame, 
            text=t('product_detail.purchase_quantity'), 
            font=('Arial', 11, 'bold')
        ).pack(side='left')
        
        self.quantity_var = tk.IntVar(value=1)
        quantity_spinbox = ttk.Spinbox(
            quantity_frame,
            from_=1,
            to=99,
            textvariable=self.quantity_var,
            width=8,
            font=('Arial', 11)
        )
        quantity_spinbox.pack(side='left', padx=(10, 0))
        
        # 操作按钮
        button_frame = customtkinter.CTkFrame(operation_frame, fg_color="transparent")
        button_frame.pack(side='right')
        
        # 加入购物车按钮
        self.add_to_cart_btn = customtkinter.CTkButton(
            button_frame,
            text=t('product_detail.add_to_cart'),
            command=self.add_to_cart,
            width=150,
            height=40,
            font=('Arial', 13, 'bold'),
            fg_color=Theme.get_color('accent'),
            hover_color=Theme.get_color('accent_hover')
        )
        self.add_to_cart_btn.pack(side='left', padx=(0, 15))
        
        # 立即购买按钮
        self.buy_now_btn = customtkinter.CTkButton(
            button_frame,
            text=t('product_detail.buy_now'),
            command=self.buy_now,
            width=150,
            height=40,
            font=('Arial', 13, 'bold'),
            fg_color='#E74C3C',
            hover_color='#C0392B'
        )
        self.buy_now_btn.pack(side='left')
    
    def load_product_data(self):
        """加载商品数据"""
        if not self.product_id:
            self.show_error("商品ID无效")
            return
        
        try:
            # 获取商品信息
            self.product = self.controller.product_service.get_product_by_id(self.product_id)
            if not self.product:
                self.show_error("商品不存在")
                return
            
            # 更新商品信息显示
            self.update_product_display()
            
            # 加载评价数据
            self.load_reviews()
            
        except Exception as e:
            error(f"加载商品数据失败: {e}")
            self.show_error(f"加载商品数据失败: {e}")
    
    def update_product_display(self):
        """更新商品信息显示"""
        if not self.product:
            return
        
        # 更新基本信息 - 使用英文名称
        product_name = self.product.get_display_name() if hasattr(self.product, 'get_display_name') else (getattr(self.product, 'name_en', None) or self.product.name)
        self.name_label.configure(text=product_name)
        self.price_label.configure(text=f"¥{self.product.price:.2f}")
        
        # 更新库存信息
        stock_color = "#27AE60" if self.product.stock > 10 else "#E67E22" if self.product.stock > 0 else "#E74C3C"
        stock_text = f"库存: {self.product.stock} 件"
        if self.product.stock > 10:
            stock_text += " ✅ 现货充足"
        elif self.product.stock > 0:
            stock_text += " ⚠️ 库存紧张"
        else:
            stock_text += " ❌ 缺货"
        
        self.stock_label.configure(text=stock_text, text_color=stock_color)
        
        # 更新商品类别
        category_text = f"类别: {self.product.get_category().title()}"
        self.category_label.configure(text=category_text)
        
        # 更新描述
        self.description_text.configure(state='normal')
        self.description_text.delete('1.0', tk.END)
        self.description_text.insert('1.0', self.product.description)
        self.description_text.configure(state='disabled')
        
        # 更新规格信息
        self.update_specifications()
        
        # 更新厂商信息
        self.update_manufacturer_info()
    
    def update_specifications(self):
        """更新商品规格信息"""
        # 清除现有规格
        for widget in self.specs_frame.winfo_children():
            widget.destroy()
        
        if not self.product:
            return
        
        # 根据商品类别显示不同规格
        specs = []
        
        if hasattr(self.product, 'brand'):
            specs.append(f"品牌: {self.product.brand}")
        if hasattr(self.product, 'warranty'):
            specs.append(f"保修: {self.product.warranty}")
        if hasattr(self.product, 'author'):
            specs.append(f"作者: {self.product.author}")
        if hasattr(self.product, 'isbn'):
            specs.append(f"ISBN: {self.product.isbn}")
        if hasattr(self.product, 'size'):
            specs.append(f"尺寸: {self.product.size}")
        if hasattr(self.product, 'color'):
            specs.append(f"颜色: {self.product.color}")
        
        if specs:
            customtkinter.CTkLabel(
                self.specs_frame, 
                text="📏 规格信息:", 
                font=('Arial', 11, 'bold'),
                text_color=Theme.get_color('fg_primary')
            ).pack(anchor='w', pady=(0, 5))
            for spec in specs:
                customtkinter.CTkLabel(
                    self.specs_frame, 
                    text=f"✓ {spec}", 
                    font=('Arial', 10),
                    text_color=Theme.get_color('fg_secondary')
                ).pack(anchor='w', padx=(10, 0), pady=2)
    
    def update_manufacturer_info(self):
        """更新厂商信息"""
        if not self.product:
            return
        
        # 这里可以根据seller_id获取厂商信息
        # 暂时使用默认信息
        seller_id = getattr(self.product, 'seller_id', 'unknown')
        self.manufacturer_name_label.configure(text=f"厂商: {seller_id}")
        self.manufacturer_info_label.configure(text="厂商详细信息暂未提供")
    
    def load_reviews(self):
        """加载评价数据"""
        try:
            info(f"🔄 开始加载商品 {self.product_id} 的评价数据")
            
            # 获取商品评价（强制刷新）
            self.reviews = self.controller.review_service.get_product_reviews(self.product_id)
            
            info(f"📝 加载到 {len(self.reviews)} 条评价")
            
            # 更新评价统计
            self.update_reviews_stats()
            
            # 更新评价列表
            self.update_reviews_list()
            
            info(f"✅ 商品 {self.product_id} 评价数据加载完成")
            
        except Exception as e:
            error(f"❌ 加载评价数据失败: {e}")
            # 显示无评价信息
            self.show_no_reviews()
    
    def update_reviews_stats(self):
        """更新评价统计"""
        # 清除现有统计
        for widget in self.reviews_stats_frame.winfo_children():
            widget.destroy()
        
        if not self.reviews:
            self.show_no_reviews()
            return
        
        # 计算统计信息
        total_reviews = len(self.reviews)
        avg_rating = sum(review.rating for review in self.reviews) / total_reviews if total_reviews > 0 else 0
        
        # 更新星级评分
        self.star_rating.set_rating(int(avg_rating))
        self.rating_text_label.configure(text=f"({total_reviews} 评价)")
        
        # 显示统计信息 - 使用CustomTkinter美化
        stats_text = f"📊 平均评分: {avg_rating:.1f} 分 | 共 {total_reviews} 条评价"
        customtkinter.CTkLabel(
            self.reviews_stats_frame,
            text=stats_text,
            font=('Arial', 13, 'bold'),
            text_color=Theme.get_color('fg_primary')
        ).pack(anchor='w', pady=(0, 8))
        
        # 显示评分分布（如果有多条评价）
        if total_reviews > 1:
            rating_dist = self.controller.product_service.get_product_rating_stats(self.product_id)
            dist_text = "📈 评分分布: "
            for i in range(5, 0, -1):
                count = rating_dist['rating_distribution'][i]
                if count > 0:
                    dist_text += f"{i}⭐({count}) "
            
            if dist_text != "📈 评分分布: ":
                customtkinter.CTkLabel(
                    self.reviews_stats_frame,
                    text=dist_text.strip(),
                    font=('Arial', 11),
                    text_color=Theme.get_color('fg_secondary')
                ).pack(anchor='w', pady=(0, 5))
    
    def update_reviews_list(self):
        """更新评价列表"""
        # 清除现有评价
        for widget in self.reviews_list_frame.winfo_children():
            widget.destroy()
        
        if not self.reviews:
            return
        
        # 按时间倒序显示评价
        sorted_reviews = sorted(self.reviews, key=lambda x: x.created_at, reverse=True)
        
        for review in sorted_reviews:
            review_card = ReviewCard(self.reviews_list_frame, review)
            review_card.pack(fill='x', pady=(0, 10))
    
    def show_no_reviews(self):
        """显示无评价信息"""
        no_reviews_label = customtkinter.CTkLabel(
            self.reviews_list_frame,
            text="💭 暂无评价，成为第一个评价的用户吧！",
            font=('Arial', 13),
            text_color=Theme.get_color('fg_tertiary')
        )
        no_reviews_label.pack(pady=30)
    
    def refresh_reviews(self):
        """刷新评价数据（供外部调用）"""
        info(f"🔄 手动刷新商品 {self.product_id} 的评价数据")
        self.load_reviews()
    
    def show_error(self, message):
        """显示错误信息"""
        error_label = customtkinter.CTkLabel(
            self.scrollable_frame,
            text=f"❌ {message}",
            font=('Arial', 15, 'bold'),
            text_color='#E74C3C'
        )
        error_label.pack(pady=50)
    
    def add_to_cart(self):
        """加入购物车"""
        if not self.product:
            messagebox.showerror("错误", "商品信息无效")
            return
        
        quantity = self.quantity_var.get()
        if quantity <= 0:
            messagebox.showwarning("警告", "请选择有效的数量")
            return
        
        try:
            # 调用购物车服务
            self.controller.shopping_cart.add_item(
                product=self.product,
                quantity=quantity
            )
            
            product_name = self.product.get_display_name() if hasattr(self.product, 'get_display_name') else (getattr(self.product, 'name_en', None) or self.product.name)
            messagebox.showinfo("Success", f"Added {product_name} x{quantity} to cart")
                
        except Exception as e:
            error(f"加入购物车失败: {e}")
            messagebox.showerror("错误", f"加入购物车时发生错误: {e}")
    
    def buy_now(self):
        """立即购买"""
        if not self.product:
            messagebox.showerror("错误", "商品信息无效")
            return
        
        quantity = self.quantity_var.get()
        if quantity <= 0:
            messagebox.showwarning("警告", "请选择有效的数量")
            return
        
        # 跳转到购物车页面进行结算
        try:
            # 先加入购物车
            self.controller.shopping_cart.add_item(
                product=self.product,
                quantity=quantity
            )
            
            # 跳转到购物车页面
            self.controller.show_page('CartPage')
            
        except Exception as e:
            error(f"立即购买失败: {e}")
            messagebox.showerror("错误", f"立即购买时发生错误: {e}")
    
    def update_data(self):
        """更新页面数据（页面切换回来时调用）"""
        if self.product_id:
            # 重新加载商品数据以获取最新库存
            self.load_product_data()
    
    def go_back(self):
        """返回上一页"""
        # 隐藏当前页面，但不销毁（由主控制器管理）
        self.grid_forget()
        # 显示商品页面
        self.controller.show_page('ProductPage')
